// pages/Orders/Orders/Orders.js
//获取应用实例
const app = getApp();
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { getGoodsOrder , queryGoodsOrderSurplusFreeUrgentTimes , applyGoodsOrderDeliveryUrgent , payGoodsOrderDeliverUrgent , queryGoodsPurchaseRecord , cancelGoodsOrder , goodsOrderPay , goodsConfirmReceipt } from '../../../api/order';
import { queryGoodsDeliveryTime , queryGoodsListTab , queryGoodsCityConfig } from '../../../api/goods';
import { queryGoodsUrgentConfig } from '../../../api/brand';
import { queryUserWechatOpenId , getUserAccount , getUser , getAddress } from '../../../api/user';
import { getToken , codeLogin } from '../../../api/login';
import { throttle } from '../../../utils/util';
import { ACCESS_TOKEN } from '../../../utils/types';
const regeneratorRuntime = require('../../../common/runtime');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareTitle: app.globalData.global.shareTitle,
    contactUrl: app.globalData.global.contactUrl,
    contactId: app.globalData.global.contactId,
    tabNavTop: app.globalData.CustomBar,
    assetsAddress: assetsAddress,
    tabList: [
      { id: '', name: '全部'},{ id: '0', name: '待付款'},{ id: '1', name: '待发货'},{ id: '2', name: '待收货'},
    ],
    active: '',
    goodsName: '', // 搜索商品名称
    page: 0,
    isReachBottom: false,
    noMore: false,
    loading: false,
    loadingFailed: false,
    dataList: [],
    urgentAmount: 0, // 商品加急费用
    freeUrgentNum: 0, // 剩余免费加急次数
    showPayUrgent: false,
    payUrgentOrder: '', // 支付加急的订单
    recordTotal: 0, // 疯抢人数
    recordList: [], // 疯抢人员列表
    goodsList: [], // 商品列表
    openId: '',
    showGoOnPay: false,
    balance: 0, // 账户余额
    payType: '',
    goOnPayOrderCode: '', // 继续支付的订单
    payPassword: '', // 支付密码
    storehouseId: wx.getStorageSync('storehouseId'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    if(options.type){
      this.setData({
        active: JSON.parse(options.type),
      })
    }
    if (wx.onNeedPrivacyAuthorization) {
      wx.onNeedPrivacyAuthorization((resolve) => {
        console.log('触发弹窗')
        // 触发弹窗
        _this.setData({
          showPrivacyAuthor: true,
        })
        _this.resolvePrivacyAuthorization = resolve
      })
    }
    if(wx.getStorageSync(ACCESS_TOKEN) == null || wx.getStorageSync(ACCESS_TOKEN) == ''){
      this.login();
    }else{
      this._queryGoodsOrderSurplusFreeUrgentTimes();
      this._queryGoodsUrgentConfig();
      this._queryGoodsPurchaseRecord();
      this._getGoods();
      this._queryUserWechatUnionId();
      this._getOrders();
      this._getUserAccount('0');
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(wx.getStorageSync('isUpdateOrder') == '1'){
      this.setData({
        page: 0,
        isReachBottom: false,
        noMore: false,
        loading: false,
        loadingFailed: false,
      })
      this._getOrders();
      wx.setStorageSync('isUpdateOrder', 0)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
    })
    this._getOrders();
    this._queryGoodsUrgentConfig();
    this._queryGoodsOrderSurplusFreeUrgentTimes();
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: throttle(function(){
    console.log('上拉加载')
    if(this.data.isReachBottom){
      this._getOrders()
    }
  },500),

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 查询订单数据
  _getOrders(){
    let _this = this;
    getGoodsOrder({orderStatus: _this.data.active,goodsName: _this.data.goodsName,page: _this.data.page,})
    .then(async (res) => {
      if(res.success){
        var data = [];
        for (let index = 0; index < res.data.content.length; index++) {
          const item = res.data.content[index];
          item.goodsInfo = JSON.parse(item.goodsInfo);
          item.receivingAddressInfo = JSON.parse(item.receivingAddressInfo);
          if((item.orderStatus == '1' || item.orderStatus == '2' ) && item.deliveryType == '0'){
            var deliveryTime = '';
            try {
              deliveryTime = await _this._queryGoodsDeliveryTime(item.receivingAddressInfo.province,item.receivingAddressInfo.city,item.receivingAddressInfo.area)
            } catch (error) {
              
            }
            console.log(deliveryTime,'delivertime')
            item.deliveryTime = deliveryTime;
          }
          data.push(item);
        }
        var list = _this.data.dataList;
        if(_this.data.page == 0){
          list = data;
        }else{
          list.concat(data);
        }
        _this.setData({
          dataList: list,
          total: res.data.totalElements,
          page: _this.data.page+1,
        })
        if(_this.data.page * 10 >= res.data.totalElements){
          _this.setData({
            isReachBottom: false,
            noMore: true,
            loading: false,
            loadingFailed: false,
          })
        }else{
          _this.setData({
            isReachBottom: true,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取商品配送时间
  _queryGoodsDeliveryTime(province,city,area){
    return new Promise((resolve,reject) => {
      queryGoodsDeliveryTime({province: province,city: city,area: area})
      .then(res => {
        if(res.success){
          resolve(res.data)
        }else{
          reject(res.errMessage)
        }
      })
    })
  },
  // tab切换
  onChange(e){
    console.log(e)
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      active: e.detail.name,
    })
    this._getOrders();
  },
  // 输入框发生变化
  onSearchChange(e) {
    this.setData({
      goodsName: e.detail,
    });
  },
  // 输入框搜索
  onSearch(){
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
    })
    this._getOrders();
  },
  // 售后
  contact(e){
    let _this = this;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(item)
    wx.setClipboardData({
      data: item.orderCode
    })
    wx.openCustomerServiceChat({
      extInfo: {
        url: _this.data.contactUrl,
      },
      corpId: _this.data.contactId,
    })
  },
  // 查询商品加急配置
  _queryGoodsUrgentConfig(){
    let _this = this;
    queryGoodsUrgentConfig({})
    .then(res => {
      if(res.success){
        if(res.data.content.length > 0){
          _this.setData({
            urgentAmount: res.data.content[0].paymentAmount,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 查询用户剩余免费加急次数
  _queryGoodsOrderSurplusFreeUrgentTimes(){
    let _this = this;
    queryGoodsOrderSurplusFreeUrgentTimes({})
    .then(res => {
      if(res.success){
        _this.setData({
          freeUrgentNum: res.data,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 申请订单加急
  applyUrgent(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    let _this = this;
      wx.showModal({
        title: '加急',
        content: _this.data.freeUrgentNum > 0 ? `本月还有${_this.data.freeUrgentNum}次免费加急次数，是否使用？` : '本月免费加急次数已使用，请联系客服支付加急费用',
        confirmText: _this.data.freeUrgentNum > 0 ? '确认使用' : '确认加急',
        confirmColor: '#F4575E',
        success: (modal)=>{
          if(modal.confirm){
            applyGoodsOrderDeliveryUrgent({orderCode: item.orderCode})
            .then(res => {
              if(res.success){
                if(res.data.orderCode){
                  if(res.data.orderStatus == '1'){
                    _this.setData({
                      showPayUrgent: true,
                      payUrgentOrder: res.data.orderCode,
                    })
                  }else if(res.data.orderStatus == '0'){
                    wx.showToast({
                      title: '订单加急已提交申请，请联系客服询问结果',
                      icon: 'success',
                    })
                  }else if(res.data.orderStatus == '3'){
                    wx.showToast({
                      title: '当前订单加急申请已被拒绝，请联系客服处理',
                      icon: 'success',
                    })
                  }
                }else{
                  wx.showToast({
                    title: '已成功申请加急',
                    icon: 'success',
                  })
                  _this._queryGoodsOrderSurplusFreeUrgentTimes();
                  _this.setData({
                    page: 0,
                    isReachBottom: false,
                    noMore: false,
                    loading: false,
                    loadingFailed: false,
                  })
                  this._getOrders();
                }
              }else{
                wx.showToast({
                  title: res.errMessage,
                  icon: 'none',
                })
              }
            })
          }
        }
      })
  },
  // 复制订单号
  copyOrderCode(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    wx.setClipboardData({
      data: item.orderCode,
      success: function(){}
    })
  },
  // 页面跳转
  goNext(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    // console.log(JSON.stringify(item))
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
        })
      }
    }
  },
  // 关闭加急支付弹框
  onClose(){
    this.setData({
      showPayUrgent: false,
      showGoOnPay: false,
    })
  },
  // 确认支付加急订单
  submitPayUrgent(){
    let _this = this;
    payGoodsOrderDeliverUrgent({orderCode: _this.data.payUrgentOrder,openId: _this.data.openId})
    .then(res => {
      if(res.success){
        // TODO微信支付
        var order = JSON.parse(res.data)
        // TODO微信支付
        wx.requestPayment({
          timeStamp: order.timeStamp.toString(),
          nonceStr: order.nonceStr,
          package: order.package,
          signType: order.signType,
          paySign: order.paySign,
          success: () => {
            _this.setData({
              page: 0,
              isReachBottom: false,
              noMore: false,
              loading: false,
              loadingFailed: false,
              showPayUrgent: false,
              showGoOnPay: false,
            })
            _this._getOrders();
            wx.showToast({
              title: '支付成功',
              icon: 'success'
            })
          },
          fail: (err) => {
            console.log(err,'err')
            wx.showToast({
              title: '取消支付',
              icon: 'none',
            })
          }
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 查询商品购买记录（包含假数据）
  _queryGoodsPurchaseRecord(){
    let _this = this;
    queryGoodsPurchaseRecord({storehouseId: _this.data.storehouseId})
    .then(res => {
      if(res.success){
        _this.setData({
          recordList: res.data.content,
          recordTotal: res.data.totalElements,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取商品列表信息
  _getGoods(){
    let _this = this;
    var storehouseId = wx.getStorageSync('storehouseId');
    queryGoodsListTab({size: 20,storehouseId: storehouseId,areaId: '0'})
    .then(res => {
      if(res.success){
        _this.setData({
          goodsList: res.data.content,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 取消订单
  closeOrder(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    // console.log(item.orderCode,'item');
    let _this = this;
    cancelGoodsOrder(item.orderCode)
    .then(res => {
      if(res.success){
        wx.showToast({
          title: '操作成功',
          icon: 'success',
        })
        _this.setData({
          page: 0,
          isReachBottom: false,
          noMore: false,
          loading: false,
          loadingFailed: false,
        })
        _this._getOrders();
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取用户的Openid
  _queryUserWechatUnionId(){
    let _this = this;
    wx.login({
      success: (logRes) => {
        queryUserWechatOpenId({code: logRes.code})
        .then(res => {
          if(res.success){
            _this.setData({
              openId: res.data.openid
            })
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      }
    })
  },
  // 继续支付
  goOnPay(e){
    let _this = this;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(item,'item')
    if(item.paidAmount > 0){
      // 如果之前是组合支付，那么继续支付就默认使用微信支付
      _this.pay({orderCode: item.orderCode,payType: 3,isMixPay: '1'});
    }else{
      _this.setData({
        showGoOnPay: true,
        payAmount: item.payAmount,
        payType: _this.data.balance < item.payAmount ? 3 : 1,
        goOnPayOrderCode: item.orderCode,
      })
    }
  },
  // 选择维信支付
  selWechatPay(e){
    let payType = e.target.dataset.type||e.currentTarget.dataset.type;
    this.setData({
      payType: payType,
    })
  },
  // 确认选择通道继续支付
  submitGoOnPay(){
    if(this.data.payType == 1){
      if(this.data.payAmount > this.data.balance){
        wx.showToast({
          title: '当前账户余额不足，请更换其他支付方式',
          icon: 'none',
        })
        return;
      }
    }
    if(this.data.payType == '1'){
      const child = this.selectComponent('.pay-passwordAuth');
      child.clearPassword();
      child.openPayAuth();
    }else{
      this.pay({orderCode: this.data.goOnPayOrderCode,payType: this.data.payType});
    }
  },
  // 余额支付校验密码成功
  sonSubmitOrder(e){
    this.setData({
      payPassword: e.detail,
    })
    this.pay({orderCode: this.data.goOnPayOrderCode,payType: this.data.payType});
  },
  pay({orderCode,payType,isMixPay,}){
    let _this = this;
    goodsOrderPay({isAllPay: '1',payType: payType,orderCode: orderCode,openId: _this.data.openId,isMixPay: isMixPay,payPassword: _this.data.payType == '1' ? _this.data.payPassword : null}).then(res => {
      if(res.success){
        _this.wechatPay({payType: payType,wechatSign: res.data});
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 支付
  wechatPay({payType,wechatSign}){
    let _this = this;
    if(payType == 1){
      _this.setData({
        page: 0,
        isReachBottom: false,
        noMore: false,
        loading: false,
        loadingFailed: false,
        showGoOnPay: false,
      })
      _this._getUserAccount('0');
      _this._getOrders();
      wx.showToast({
        title: '支付成功',
        icon: 'success'
      })
    }else{
      // console.log(JSON.parse(wechatSign),'jsonData');
      var order = JSON.parse(wechatSign)
      // TODO微信支付
      wx.requestPayment({
        timeStamp: order.timeStamp.toString(),
        nonceStr: order.nonceStr,
        package: order.package,
        signType: order.signType,
        paySign: order.paySign,
        success: () => {
          _this.setData({
            page: 0,
            isReachBottom: false,
            noMore: false,
            loading: false,
            loadingFailed: false,
            showGoOnPay: false,
          })
          _this._getOrders();
          wx.showToast({
            title: '支付成功',
            icon: 'success'
          })
        },
        fail: (err) => {
          console.log(err,'err')
          wx.showToast({
            title: '取消支付',
            icon: 'none',
          })
        }
      })
    }
  },
  // 获取用户账户余额
  _getUserAccount(type){
    let _this = this;
    getUserAccount(type)
    .then(res => {
      if(res.success){
        if(type == 0){
          _this.setData({
            balance : res.data.balance,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  // 确认收货
  confirmReceipt(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    let _this = this;
    wx.showModal({
      title: '温馨提示',
      content: '是否确认收货？',
      success: (modal) => {
        if(modal.confirm){
          goodsConfirmReceipt(item.orderCode)
          .then(res => {
            if(res.success){
              wx.showToast({
                title: '操作成功',
                icon: 'success',
              })
              wx.setStorageSync('isUpdateOrder', 1)
              wx.navigateTo({
                url: '/pages/Goods/EvaluationEvent/EvaluationEvent?item=' + JSON.stringify(item),
              })
            }else{
              wx.showToast({
                title: res.errMessage,
                icon: 'none',
              })
            }
          })
        }
      }
    })
  },
  handleAgreePrivacyAuthorizationFun(){
    console.log('同意之后的回调');
    // this.getUserAddress();
  },
  disagreePrivacyAuthorization(){
    this.resolvePrivacyAuthorization({ event: 'disagree' });
  },
  // 登录
  login(){
    var expires_in = wx.getStorageSync('expires_in');
    console.log(expires_in,'expires_in');
    // 获取服务器token
    getToken().then(res => {
      let _this = this;
      if(res.success){
          wx.setStorageSync(ACCESS_TOKEN, res[ACCESS_TOKEN]);
          // 登录
          wx.login({
            success: logRes => {
              // 发送 res.code 到后台换取 openId, sessionKey, unionId
              console.log(logRes,'logRes')
              if (logRes.code) {
                codeLogin(logRes.code,_this.data.parentUserId)
                .then(rres => {
                  console.log(rres,'第一次登录返回的rres')
                  if(rres.success){
                      wx.setStorageSync(ACCESS_TOKEN, rres.access_token);
                      wx.setStorageSync('expires_in', rres.expires_in);
                      setTimeout(() => {
                        getUser()
                        .then(user => {
                          if(user.success){
                            wx.setStorageSync('userId', user.data.userId)
                            wx.setStorageSync('phone', user.data.phone)
                            _this._queryGoodsOrderSurplusFreeUrgentTimes();
                            _this._queryGoodsUrgentConfig();
                            _this._queryGoodsPurchaseRecord();
                            _this.getUserAddress();
                            _this._queryUserWechatUnionId();
                            _this._getOrders();
                            _this._getUserAccount('0');
                          }
                        })
                      }, 500);
                  }
                })
              } else {
                wx.showToast({
                  title: logRes.errMsg,
                  icon: 'none',
                })
              }
            },
          })
      }else{
          wx.showToast({
              title: res.errMessage,
              icon: 'none'
          })
      }
    })
  },
  // 定位
  async getUserAddress(){
    var _this = this;
    try {
      var arr = await _this._getAddress();
      console.log(arr,'地址arr')
      if(arr.length > 0){
        _this._queryGoodsCityConfig();
        return;
      }
    } catch (error) {
      
    }
  },
  // 获取用户收货地址
  _getAddress(){
    let _this = this;
    return new Promise((resolve,reject) => {
      getAddress({})
      .then(res => {
        if(res.success){
          if(res.data.length > 0){
            var address = res.data[0];
            for (let index = 0; index < res.data.length; index++) {
              const item = res.data[index];
              if(item.isDefault == '1'){
                address = item;
              }
            }
            _this.setData({
              province: address.province,
              city: address.city,
              country: address.area,
            })
            resolve(res.data)
          }else{
            resolve([])
          }
        }else{
          reject(res.errMessage)
        }
      })
    })
  },
  // 获取商品城市配置（仓库）
  _queryGoodsCityConfig(){
    let _this = this;
    var {province , city , country} = _this.data;
    queryGoodsCityConfig({province: province,city: city,area: country})
    .then(res => {
      if(res.success){
        if(res.data.content.length > 0){
          _this.setData({
            storehouseId: res.data.content[0].storehouseId,
          })
          wx.setStorageSync('storehouseId', res.data.content[0].storehouseId)
          wx.setStorageSync('storehouseName', res.data.content[0].storehouseName)
          _this._getGoods();
        }else{
          queryGoodsCityConfig({})
          .then(res => {
            if(res.success){
              if(res.data.content.length > 0){
                _this.setData({
                  storehouseId: res.data.content[0].storehouseId,
                })
                wx.setStorageSync('storehouseId', res.data.content[0].storehouseId)
                _this._getGoods();
              }else{
                wx.showToast({
                  title: '当前地区暂无仓库配置',
                  icon: 'none',
                })
              }
            }else{
              wx.showToast({
                title: res.errMessage,
                icon: 'none'
              })
            }
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
})